package com.ranga.mselfcare;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ranga.mselfcare.config.Config;
import com.ranga.mselfcare.services.TokenService;

@SuppressLint("HandlerLeak")
public class TokenInitializeActivity extends Activity implements
		OnClickListener {

	private EditText txtPhoneNumber;
	private Button btnGetToken;
	private ProgressDialog progressDialog;
	private static final String TAG = "TokenInitializeActivity";
	private int status = Config.PROGRESS_STOPPED;
	private String phoneNumber = "";
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_token_initialize);

		txtPhoneNumber = (EditText) findViewById(R.id.et_phoneNumber);
		btnGetToken = (Button) findViewById(R.id.b_getToken);
		btnGetToken.setOnClickListener(this);
		
		progressDialog = new ProgressDialog(this);
		progressDialog.setCanceledOnTouchOutside(false);

	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(Config.STATUS, status);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		status = savedInstanceState.getInt(Config.STATUS);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (status == Config.PROGRESS_STARTED) {
			progressDialog.show();
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		hideProgressDialog();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.b_getToken:
			if (validateFields()) {
				if (isNetworkAvailable()) {
					if (status == Config.PROGRESS_STOPPED) {
						phoneNumber = txtPhoneNumber.getText().toString();
						Log.w(TAG, "Phone Number: " + phoneNumber);
						
						Intent loginServiceIntent = new Intent(this, TokenService.class);
						Messenger resultMessenger = new Messenger(serviceResultHandler);
						Messenger progressMessenger = new Messenger(progressHandler);
						Bundle bundle = new Bundle();
						bundle.putString(Config.PHONE_NUMBER, phoneNumber);
						try {
							Log.w(TAG, "inside try");
							loginServiceIntent.putExtras(bundle);
							loginServiceIntent.putExtra(Config.RESULT_MESSENGER, resultMessenger);
							loginServiceIntent.putExtra(Config.PROGRESS_MESSENGER, progressMessenger);
							startService(loginServiceIntent);
						} catch (SecurityException e) {
							Log.w(TAG, "Unable to start get token service: " + e.toString());
						}
					}
				}
			}
			
			break;
		}

	}

	private boolean validateFields() {
		String phoneNumber = txtPhoneNumber.getText().toString();
		boolean verified = false;
		if (phoneNumber != null) {
			if (!phoneNumber.trim().isEmpty()) {
				verified = true;
			} else {
				verified = false;
				showToast(this, "You need to enter your phone number",
						Toast.LENGTH_SHORT);
				txtPhoneNumber.setFocusable(true);
				txtPhoneNumber.requestFocus();
			}
		} else {
			verified = false;
			showToast(this, "You need to enter your phone number",
					Toast.LENGTH_SHORT);
			txtPhoneNumber.setFocusable(true);
			txtPhoneNumber.requestFocus();
		}

		return verified;
	}

	private void showToast(Context context, String message, int length) {
		Toast.makeText(context, message, length).show();
	}
	
	@Override
	public void onBackPressed() {
		AlertDialog.Builder alertExit = new AlertDialog.Builder(this);
		alertExit.setTitle(getString(R.string.alert));
		alertExit.setMessage(getString(R.string.alert_exit));
		alertExit.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
				
			}
		});
		alertExit.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				
			}
		});
		alertExit.show();
	}
	
	private Handler progressHandler = new Handler() {
	    public void handleMessage(Message message) {
	    	
	    	status = message.arg1;
	    	
	    	switch (status) {
	    	
	    	case Config.PROGRESS_STARTED: 
	    		Log.i(TAG, "Progress Started");
	    		progressDialog.setMessage(TokenInitializeActivity.this.getString(R.string.getting_token));
	    		progressDialog.show();
	    		break;
	    		
	    	case Config.PROGRESS_STOPPED:
	    		Log.i(TAG, "Progress stopped");
	    		hideProgressDialog();
	    		status = Config.PROGRESS_STOPPED;
	    		Toast.makeText(TokenInitializeActivity.this, "Error getting token!", Toast.LENGTH_SHORT).show();
	    		break;
	    	case Config.PROGRESS_SUCCESS:
	    		Log.i(TAG, "Progress success");
	    		hideProgressDialog();
	    		status = Config.PROGRESS_STOPPED;
	    		break;
	    	}
	    };
	};
	
	private Handler serviceResultHandler = new Handler() {
	    public void handleMessage(Message message) {
	      Bundle resultBundle = message.getData();
	      String token = "";
	      int errorCode = 0;
	      if (resultBundle.containsKey(Config.TOKEN)) {
	    	  token = resultBundle.getString(Config.TOKEN);
	      }
	      if (resultBundle.containsKey(Config.RESPONSE_ERROR)) {
	    	  errorCode = Integer.parseInt(resultBundle.getString(Config.RESPONSE_ERROR));
	      }
	      Log.w(TAG, "Token Recieved: " + token);
	      
	      if (errorCode == 200) {
	    	  Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
	    	  editor.putString(Config.TOKEN, token);
	    	  boolean tokenSaved = editor.commit();
	    	  editor.putString(Config.PHONE_NUMBER, phoneNumber);
	    	  boolean phoneNumberSaved = editor.commit();
	    	  if (tokenSaved && phoneNumberSaved) {
	    		  Intent intent = new Intent(TokenInitializeActivity.this, LoginActivity.class);
	    		  finish();
	    		  startActivity(intent);
	    	  } else {
	    		  displayErrorMessage(R.string.alert_token_not_saved);
	    		  status = Config.PROGRESS_STOPPED;
	    	  }
	      } else if (errorCode == 403) {
	    	  displayErrorMessage(R.string.alert_invalid_subscriber);
	    	  status = Config.PROGRESS_STOPPED;
	      } else {
	    	  displayErrorMessage(R.string.alert_token_recieving_failed);
	    	  status = Config.PROGRESS_STOPPED;
	      }
	    };
	  };
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
	    
	   
	    boolean networkAvailable = false;
	    
	    if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
	    	networkAvailable = true;
	    } else {
	    	AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
	    	alertDialog.setTitle(getString(R.string.alert));
	    	alertDialog.setMessage(getString(R.string.no_internet_connectivity));
	    	alertDialog.setPositiveButton(getString(R.string.okay), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
				}
			});
	    	alertDialog.show();
	    }
	    return networkAvailable;
	}
	
	private void displayErrorMessage(int message){
		 AlertDialog.Builder alertDialog = new AlertDialog.Builder(TokenInitializeActivity.this);
	    	alertDialog.setTitle(getString(R.string.alert));
	    	alertDialog.setMessage(getString(message));
	    	alertDialog.setPositiveButton(getString(R.string.okay), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
	    	alertDialog.show();
	}
	
	private void hideProgressDialog() {
		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
}
